package com.fr.plugin;

import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.AbstractEmbedRequestFilterProvider;
import com.fr.decision.webservice.utils.DecisionServiceConstants;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.transform.ExecuteFunctionRecord;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.stable.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;

@FunctionRecorder
public class MyEmbedRequestFilter extends AbstractEmbedRequestFilterProvider {
    @Override
    @ExecuteFunctionRecord
    public void filter(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
        if(!isLogged(httpServletRequest)){
            // 获取token
            String myToken = httpServletRequest.getParameter("my_token");
            // 判断token是否为空
            if(StringUtils.isNotBlank(myToken)){
                try{
                    String userName = new String(Base64.getUrlDecoder().decode(myToken));
                    UserService userService = UserService.getInstance();
                    // 检查用户是否存在
                    User user = userService.getUserByUserName(userName);
                    if(user != null){
                        // 登录并设置token到请求中
                        String token = LoginService.getInstance().login(httpServletRequest, httpServletResponse, userName);
                        httpServletRequest.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, token);
                    }
                    FineLoggerFactory.getLogger().info("{} login success from my filter",userName);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    private boolean isLogged(HttpServletRequest request){
        return LoginService.getInstance().isLogged(request);
    }

}
